﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRM.Admin.Contracts.Contract.Customer;
using CRM.Admin.Contracts.Dto.Customer;
using CRM.Admin.Contracts.Model.Customer;
using KingsSharp.Common;
using KingsSharp.Common.Data;
using KingsSharp.Common.Extensions;
using KingsSharp.Core;
using KingsSharp.Core.Data;
using KingsSharp.Core.Data.Entity;

namespace CRM.Admin.Services.Service.Customer
{
    public class CustomerService : ServiceBase, ICustomerService
    {
        private IRepository<Contracts.Model.Customer.Customer, Guid> customerRepository;
        private IRepository<LinkMan, Guid> linkManRepository;
        private IRepository<CustomerNature, Guid> customerNatureRepository;
        public CustomerService(IRepository<Contracts.Model.Customer.Customer, Guid> _customerRepository,
            IRepository<LinkMan, Guid> _linkManRepository,
            IRepository<CustomerNature, Guid> _customerNatureRepository)
            : base(_customerRepository.UnitOfWork)
        {
            customerRepository = _customerRepository;
            linkManRepository = _linkManRepository;
            customerNatureRepository = _customerNatureRepository;
        }

        public IQueryable<Contracts.Model.Customer.Customer> Customers { get { return customerRepository.Entities; } }

        public OperationResult Delete(params Guid[] ids)
        {
            var entitys = customerRepository.Entities.Where(a => ids.Contains(a.Id)).ToList();
            entitys.ForEach(a => a.IsDeleted = true);
            int result = customerRepository.Update(entitys.ToArray());
            return new KingsSharp.Common.Data.OperationResult(KingsSharp.Common.Data.OperationResultType.Success, "删除成功");
        }

        public OperationResult Insert(params CustomerDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            CustomerAddress address = null;
            foreach (var t in dtos)
            {
                t.Id = Guid.NewGuid();

                address = new CustomerAddress()
                {
                    Id = Guid.NewGuid(),
                    CustomerId = t.Id,
                    Province = t.Province,
                    ProvinceCode = t.ProvinceCode,
                    City = t.City,
                    CityCode = t.CityCode,
                    Borough = t.Borough,
                    BoroughCode = t.BoroughCode,
                    Description = t.AddressDescription,
                    Province1 = t.Province1,
                    ProvinceCode1 = t.ProvinceCode1,
                    City1 = t.City1,
                    CityCode1 = t.CityCode1,
                    Borough1 = t.Borough1,
                    BoroughCode1 = t.BoroughCode1,
                    Description1 = t.AddressDescription1,
                    PostCode = t.PostCode,


                };
            }
            var result = customerRepository.Insert(dtos, dto =>
            {
                if (Customers.Any(entity => entity.Name == dto.Name && entity.IsDeleted == false))
                {
                    throw new Exception("顾客名称 {0} 重复，无法保存".FormatWith(dto.Name));
                }

            }, (dto, model) =>
            {
                model.CustomerAddress = address;
                model.CustomerAddressId = address.Id;
                model.Code = GetMaxCode();
                return model;
            });
            return result;
        }
        private string GetMaxCode()
        {
            var code = "C";
            var model =
                customerRepository.Entities
                    .OrderByDescending(a => a.CreatedTime).FirstOrDefault(entity => entity.Code != null);
            if (model != null)
            {
                var nb = model.Code.Split(code).Last().CastTo(0);
                nb++;
                code = code + nb.ToString().PadLeft(6, '0');
            }
            else
            {
                code += "000001";
            }
            return code;
        }
        public OperationResult Update(params CustomerDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            CustomerAddress address = null;
            foreach (var t in dtos)
            {
                address = new CustomerAddress()
                {
                    CustomerId = t.Id,
                    Province = t.Province,
                    ProvinceCode = t.ProvinceCode,
                    City = t.City,
                    CityCode = t.CityCode,
                    Borough = t.Borough,
                    BoroughCode = t.BoroughCode,
                    Description = t.AddressDescription,
                    Province1 = t.Province1,
                    ProvinceCode1 = t.ProvinceCode1,
                    City1 = t.City1,
                    CityCode1 = t.CityCode1,
                    Borough1 = t.Borough1,
                    BoroughCode1 = t.BoroughCode1,
                    Description1 = t.AddressDescription1,
                    PostCode = t.PostCode

                };
            }
            var result = customerRepository.Update(dtos, dto =>
            {
                if (Customers.Any(entity => entity.IsDeleted == false && entity.Name == dto.Name && entity.Id != dto.Id))
                {
                    throw new Exception("顾客名称 {0} 重复，无法保存".FormatWith(dto.Name));
                }

            }, (dto, model) =>
            {
                model.CustomerAddress.Province = address.Province;
                model.CustomerAddress.ProvinceCode = address.ProvinceCode;
                model.CustomerAddress.City = address.City;
                model.CustomerAddress.CityCode = address.CityCode;
                model.CustomerAddress.Borough = address.Borough;
                model.CustomerAddress.BoroughCode = address.BoroughCode;
                model.CustomerAddress.Description = address.Description;
                model.CustomerAddress.Province1 = address.Province1;
                model.CustomerAddress.ProvinceCode1 = address.ProvinceCode1;
                model.CustomerAddress.City1 = address.City1;
                model.CustomerAddress.CityCode1 = address.CityCode1;
                model.CustomerAddress.Borough1 = address.Borough1;
                model.CustomerAddress.BoroughCode1 = address.BoroughCode1;
                model.CustomerAddress.Description1 = address.Description1;
                model.CustomerAddress.PostCode = address.PostCode;
                return model;
            });
            return result;
        }
    }
}
